from flask import Blueprint, request
from common.libs.Helper import ops_renderJSON, ops_renderErrJSON, iPagenation, ops_render
from common.models.seal_order import SealOrder
from common.models.department import Department
from common.models.user import User
from common.models.project import Project
from application import db, app
from common.libs.DataHelper import getCurrentTime, getCurrentDate
from flask import json
import datetime
from sqlalchemy import func
import requests
import urllib.request
import flask_excel as excel

seal_page = Blueprint("seal_page", __name__)


def generatefileSn(uid):
    uid = uid
    user = User.query.filter_by(id=uid).first()
    dep = user.department
    com = user.company
    depobject = Department.query.filter_by(department=dep, company=com).first()
    depid = depobject.id
    depname = depobject.name
    lastdata = SealOrder.query.filter_by(type="文件", depid=depid).order_by(SealOrder.id.desc()).first()

    if not lastdata:
        newsn = depname + str(getCurrentDate()) + "-" + "1"
        return newsn, depid
    else:
        lastdate = lastdata.filesn[2:12]
        lastnum = int(lastdata.filesn[13:16])
        if getCurrentDate() == lastdate:
            num = lastnum + 1
            newsn = depname + str(getCurrentDate()) + "-" + str(num)
            return newsn, depid
        else:
            newsn = depname + str(getCurrentDate()) + "-" + "1"
            return newsn, depid


def generatehtSn(uid):
    uid = uid
    user = User.query.filter_by(id=uid).first()
    dep = user.department
    com = user.company
    depobject = Department.query.filter_by(department=dep, company=com).first()
    depid = depobject.id
    depname = depobject.name2
    lastdata = SealOrder.query.filter_by(type="合同", depid=depid).order_by(SealOrder.id.desc()).first()
    if not lastdata:
        newsn = "晋富" + depname + "字[" + str(datetime.datetime.now().year) + "]第001号"
        return newsn, depid
    else:
        lastnum = int(lastdata.htsn[-4:-1])
        num = lastnum + 1
        num = "%03d" % num
        newsn = "晋富" + depname + "字[" + str(datetime.datetime.now().year) + "]" + num + "号"
        return newsn, depid


@seal_page.route("/sealorder", methods=["GET", "POST"])
def sealorder():
    req = request.values
    uid = req['uid'] if "uid" in req else ""
    content = req['content'] if "content" in req else ""
    content = str(content)
    content1 = json.loads(content)
    lastdata = SealOrder.query.order_by(SealOrder.id.desc()).first()
    pdnum = int(lastdata.pdnum) + 1

    if len(uid) < 1:
        return ops_renderErrJSON(msg=content1)
    if len(content) < 1:
        return ops_renderErrJSON(msg="信息不完整")

    for item in content1:
        if item["type"] == "合同":
            htsn, depid = generatehtSn(uid=uid)
            seal_order = SealOrder()
            seal_order.pdnum = pdnum
            seal_order.type = item["type"]
            seal_order.htsn = htsn
            seal_order.name = item["name"]
            seal_order.aname = item["aname"]
            seal_order.bname = item["bname"]
            seal_order.num = item["num"]
            seal_order.dfnum = item["dfnum"]
            seal_order.cwnum = item["cwnum"]
            seal_order.cdnum = item["cdnum"]
            seal_order.filename = item["filename"]
            seal_order.filenum = item["filenum"]
            seal_order.project = item["project"]
            seal_order.depid = depid
            seal_order.mark = 1
            seal_order.uid = uid
            seal_order.created_time = seal_order.updated_time = getCurrentTime()
            db.session.add(seal_order)
            db.session.commit()
        if item["type"] == "文件":
            filesn, depid = generatefileSn(uid=uid)
            seal_order = SealOrder()
            seal_order.pdnum = pdnum
            seal_order.filesn = filesn
            seal_order.type = item["type"]
            seal_order.name = item["name"]
            seal_order.num = item["num"]
            seal_order.mark = 1
            seal_order.uid = uid
            seal_order.depid = depid
            seal_order.created_time = seal_order.updated_time = getCurrentTime()
            db.session.add(seal_order)
            db.session.commit()
    return ops_renderJSON(msg="成功", code=200)


def placeNone(a):
    a = a
    if a == "None":
        b = 0
    else:
        b = a
    return b


# 管理员获得用印申请列表
@seal_page.route("/getsealorderlist", methods=["GET", "POST"])
def getsealorderlist():

    a = SealOrder.query.filter(SealOrder.mark == 1).with_entities(SealOrder.pdnum, SealOrder.uid,
                                                                  SealOrder.created_time).distinct().all()

    rts = []
    for item in a:
        # htnum = SealOrder.query.filter(SealOrder.pdnum == item.pdnum, SealOrder.mark == 1,
        #                                SealOrder.type == "合同").count()
        # filenum = SealOrder.query.filter(SealOrder.pdnum == item.pdnum, SealOrder.mark == 1,
        #                                  SealOrder.type == "文件").count()
        # htnumall = str(SealOrder.query.filter(SealOrder.pdnum == item.pdnum, SealOrder.mark == 1,
        #                                       SealOrder.type == "合同").with_entities(func.sum(SealOrder.num)).scalar())
        # filenumall = str(SealOrder.query.filter(SealOrder.pdnum == item.pdnum, SealOrder.mark == 1,
        #                                         SealOrder.type == "文件").with_entities(func.sum(SealOrder.num)).scalar())
        # htnumall = placeNone(htnumall)
        # filenumall = placeNone(filenumall)
        time = str(item.created_time)

        b = SealOrder.query.filter(SealOrder.pdnum == item.pdnum).all()
        list = []
        for item in b:
            temp = dict(name=item.name, type=item.type, num=item.num, htsn=item.htsn, filesn=item.filesn,
                        aname=item.aname, bname=item.bname, filename=item.filename)
            list.append(temp)

        user = User.query.filter_by(id=item.uid).first()
        name = user.nickname
        dep = user.department
        com = user.company
        openid = user.openid
        phone = user.phone
        temp = dict(name=name, pdnum=item.pdnum, department=dep, company=com, time=time, openid=openid, list=list,
                    phone=phone)
        # temp = dict(name=name, pdnum=item.pdnum, department=dep, company=com, htnum=htnum, filenum=filenum,
        #             htnumall=htnumall,
        #             filenumall=filenumall, time=time, openid=openid,list=list)
        rts.append(temp)
    # rts = json.dumps(a, cls=AlchemyEncoder,ensure_ascii=False)
    return json.dumps(rts, ensure_ascii=False)  # rts


# 管理员查看存档
@seal_page.route("/getusedsealorderlist", methods=["GET", "POST"])
def getusedsealorderlist():
    req = request.values
    stime = req['stime'] if "stime" in req else ""
    etime = req['etime'] if "etime" in req else ""
    mark = req['mark'] if "mark" in req else ""
    stime=stime+" 00:00:00"
    etime=etime+" 00:00:00"

    a = SealOrder.query.filter(SealOrder.mark == 2, SealOrder.updated_time <= etime,
                               SealOrder.updated_time >= stime).with_entities(SealOrder.pdnum, SealOrder.uid,
                                                                              SealOrder.created_time).distinct().all()
    rts = []
    for item in a:
        # htnum = SealOrder.query.filter(SealOrder.pdnum == item.pdnum, SealOrder.mark == 1,
        #                                SealOrder.type == "合同").count()
        # filenum = SealOrder.query.filter(SealOrder.pdnum == item.pdnum, SealOrder.mark == 1,
        #                                  SealOrder.type == "文件").count()
        # htnumall = str(SealOrder.query.filter(SealOrder.pdnum == item.pdnum, SealOrder.mark == 1,
        #                                       SealOrder.type == "合同").with_entities(func.sum(SealOrder.num)).scalar())
        # filenumall = str(SealOrder.query.filter(SealOrder.pdnum == item.pdnum, SealOrder.mark == 1,
        #                                         SealOrder.type == "文件").with_entities(func.sum(SealOrder.num)).scalar())
        # htnumall = placeNone(htnumall)
        # filenumall = placeNone(filenumall)
        time = str(item.created_time)

        b = SealOrder.query.filter(SealOrder.pdnum == item.pdnum,SealOrder.mark == 2).all()
        list = []
        for item in b:
            temp = dict(name=item.name, type=item.type, num=item.num, htsn=item.htsn, filesn=item.filesn,
                        aname=item.aname, bname=item.bname, filename=item.filename,id=item.id)
            list.append(temp)

        user = User.query.filter_by(id=item.uid).first()
        name = user.nickname
        dep = user.department
        com = user.company
        openid = user.openid
        phone = user.phone
        temp = dict(name=name, pdnum=item.pdnum, department=dep, company=com, time=time, openid=openid, list=list,
                    phone=phone)
        # temp = dict(name=name, pdnum=item.pdnum, department=dep, company=com, htnum=htnum, filenum=filenum,
        #             htnumall=htnumall,
        #             filenumall=filenumall, time=time, openid=openid,list=list)
        rts.append(temp)
    # rts = json.dumps(a, cls=AlchemyEncoder,ensure_ascii=False)
    return json.dumps(rts, ensure_ascii=False)  # rts


@seal_page.route('/getproject', methods=['GET', 'POST'])
def getProject():
    a = Project.query.with_entities(Project.name).distinct().all()
    rts = []
    for item in a:
        temp = dict(project=item.name)
        rts.append(temp)
    # rts = json.dumps(a, cls=AlchemyEncoder,ensure_ascii=False)
    return json.dumps(rts, ensure_ascii=False)  # rts


@seal_page.route('/pushmessage', methods=['GET', 'POST'])
def pushMessage():
    req = request.values
    openid = req['openid'] if "openid" in req else ""
    pdnum = req['pdnum'] if "pdnum" in req else ""

    appID = 'wx15624353af4493ad'  # 开发者关于微信小程序的appID
    appSecret = 'd7f09203305d4afe4716c0bdaa6fe7c7'  # 开发者关于微信小程序的appSecret
    req_params = {
        'appid': appID,
        'secret': appSecret,
        'grant_type': "client_credential"
    }
    wx_login_api = 'https://api.weixin.qq.com/cgi-bin/token?'
    response_data = requests.get(wx_login_api, params=req_params)  # 向API发起GET请求
    resData = response_data.json()
    token = resData['access_token']  # 得到用户关于当前小程序的OpenID

    data = {
        "touser": openid,
        "template_id": "MwWGcwZYx2EwvFJTx4_D7hVTB6X32lwsQXApFZGmlUY",
        "page": "pages/index/index",
        # "page": "pages/seal/sealmeg?pdnum=" + str(pdnum),
        "miniprogram_state": "formal",
        "lang": "zh_CN",
        "data": {
            "thing1": {
                "value": "请您现在前往太原富力中心22层使用印鉴"
            },
            "thing4": {
                "value": "太原印鉴管理员"
            },
            "time5": {
                "value": str(getCurrentTime())
            },
        }
    }

    url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={serverToken}'.format(
        serverToken=token)
    # 数据格式化(从这里开始对上面的data进行格式化,转成符合post的json参数形式)
    data = json.dumps(data)
    # 数据格式化
    data = bytes(data, 'utf8')
    # 数据格式化

    request1 = urllib.request.Request(url)
    # post服务器请求
    result = urllib.request.urlopen(request1, data).read()
    # 打印结果
    newresult = json.loads(result)
    errcode = newresult['errcode']
    if errcode == 0:
        pdnum = req['pdnum'] if "pdnum" in req else ""
        a = SealOrder.query.filter_by(pdnum=pdnum).all()
        for item in a:
            item.mark = 2
            item.updated_time = getCurrentTime()
            db.session.commit()
        return ops_renderJSON(msg="叫号成功")

    if errcode == 43101:
        pdnum = req['pdnum'] if "pdnum" in req else ""
        a = SealOrder.query.filter_by(pdnum=pdnum).all()
        for item in a:
            item.mark = 0
            item.updated_time = getCurrentTime()
            db.session.commit()
        return ops_renderJSON(msg="员工拒绝接受通知")


@seal_page.route('/pushdeny', methods=['GET', 'POST'])
def pushDeny():
    req = request.values
    openid = req['openid'] if "openid" in req else ""
    pdnum = req['pdnum'] if "pdnum" in req else ""

    appID = 'wx15624353af4493ad'  # 开发者关于微信小程序的appID
    appSecret = 'd7f09203305d4afe4716c0bdaa6fe7c7'  # 开发者关于微信小程序的appSecret
    req_params = {
        'appid': appID,
        'secret': appSecret,
        'grant_type': "client_credential"
    }
    wx_login_api = 'https://api.weixin.qq.com/cgi-bin/token?'
    response_data = requests.get(wx_login_api, params=req_params)  # 向API发起GET请求
    resData = response_data.json()
    token = resData['access_token']  # 得到用户关于当前小程序的OpenID

    data = {
        "touser": openid,
        "template_id": "MwWGcwZYx2EwvFJTx4_D7hVTB6X32lwsQXApFZGmlUY",
        "page": "pages/seal/sealmeg?pdnum=" + str(pdnum),
        "miniprogram_state": "formal",
        "lang": "zh_CN",
        "data": {
            "thing1": {
                "value": "您的登记信息有误，请重新申请"
            },
            "thing4": {
                "value": "太原印鉴管理员"
            },
            "time5": {
                "value": str(getCurrentTime())
            },
        }
    }

    url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={serverToken}'.format(
        serverToken=token)
    # 数据格式化(从这里开始对上面的data进行格式化,转成符合post的json参数形式)
    data = json.dumps(data)
    # 数据格式化
    data = bytes(data, 'utf8')
    # 数据格式化

    request1 = urllib.request.Request(url)
    # post服务器请求
    result = urllib.request.urlopen(request1, data).read()
    # 打印结果
    newresult = json.loads(result)
    errcode = newresult['errcode']
    if errcode == 0:
        pdnum = req['pdnum'] if "pdnum" in req else ""
        a = SealOrder.query.filter_by(pdnum=pdnum).all()
        for item in a:
            item.mark = 0
            db.session.commit()
        return ops_renderJSON(msg="驳回成功")

    if errcode == 43101:
        pdnum = req['pdnum'] if "pdnum" in req else ""
        a = SealOrder.query.filter_by(pdnum=pdnum).all()
        for item in a:
            item.mark = 0
            db.session.commit()
        return ops_renderJSON(msg="员工拒绝接受通知")


# 申请页面获得已申请列表
@seal_page.route("/usergetsealorderlist", methods=["GET", "POST"])
def usergetsealorderlist():
    req = request.values
    uid = req['uid'] if "uid" in req else ""
    a = SealOrder.query.filter(SealOrder.mark == 1, SealOrder.uid == uid).with_entities(SealOrder.pdnum,
                                                                                        SealOrder.created_time).distinct().all()
    rts = []
    for item in a:
        time = str(item.created_time)
        time = time[0:10]

        temp = dict(time=time, pdnum=item.pdnum, url="../seal/sealdetail?pdnum=" + str(item.pdnum))
        rts.append(temp)
    # rts = json.dumps(a, cls=AlchemyEncoder,ensure_ascii=False)
    return json.dumps(rts, ensure_ascii=False)  # rts


# 用户获得用印申请详细信息和排队时间
@seal_page.route("/getsealorderdetail", methods=["GET", "POST"])
def getsealorderdetail():
    req = request.values
    pdnum = req['pdnum'] if "pdnum" in req else ""
    a = SealOrder.query.filter_by(pdnum=pdnum, mark=1).all()

    # 计算排队人数和排队时间
    peoplenum = str(SealOrder.query.filter(SealOrder.pdnum < pdnum, SealOrder.mark == 1).with_entities(
        SealOrder.pdnum).distinct().count())
    filenum = str(SealOrder.query.filter(SealOrder.pdnum < pdnum, SealOrder.mark == 1).with_entities(
        func.sum(SealOrder.num)).scalar())
    peoplenum = placeNone(peoplenum)
    filenum = placeNone(filenum)
    waitingtime = int(filenum) * 5

    # 返回list信息
    rts = []
    for item in a:
        temp = dict(type=item.type, name=item.name, peoplenum=peoplenum, num=item.num, waitingtime=waitingtime,
                    id=item.id)
        rts.append(temp)
    # rts = json.dumps(a, cls=AlchemyEncoder,ensure_ascii=False)
    return json.dumps(rts, ensure_ascii=False)  # rts


# 通知页面
@seal_page.route("/getsealordermeg", methods=["GET", "POST"])
def getsealordermeg():
    req = request.values
    pdnum = req['pdnum'] if "pdnum" in req else ""
    a = SealOrder.query.filter(SealOrder.pdnum == pdnum, SealOrder.mark != 0).all()

    # 返回list信息
    rts = []
    for item in a:
        temp = dict(type=item.type, name=item.name, num=item.num, id=item.id, mark=item.mark)
        rts.append(temp)
    # rts = json.dumps(a, cls=AlchemyEncoder,ensure_ascii=False)
    return json.dumps(rts, ensure_ascii=False)  # rts


@seal_page.route("/changesealmark", methods=["GET", "POST"])
def changesealmark():
    req = request.values
    id = req['id'] if "id" in req else ""
    mark = req['mark'] if "mark" in req else ""
    a = SealOrder.query.filter_by(id=id).first()
    a.mark = mark
    db.session.commit()
    return ops_renderJSON(msg="该条记录已删除")


@seal_page.route("/changesealallmark", methods=["GET", "POST"])
def changesealallmark():
    req = request.values
    pdnum = req['pdnum'] if "pdnum" in req else ""
    mark = req['mark'] if "mark" in req else ""
    a = SealOrder.query.filter_by(pdnum=pdnum).all()
    for item in a:
        item.mark = mark
        db.session.commit()
    return ops_renderJSON(msg="用印申请已作废")




def pagessearch(seal, stime, etime):
    req = request.values
    stime = stime
    etime = etime
    page = 1
    if 'p' in req and req['p']:
        page = int(req['p'])

    page_params = {
        'total_count': seal.count(),
        "page_size": 14,
        'page': page,
        'url': "/seal/htsearch?starttime=" + stime + "&endtime=" + etime,
    }
    pages = iPagenation(page_params)
    # -1 - 30,30 - 60 ,60 - 90
    offset = (page - 1) * page_params['page_size']
    limit = page * page_params['page_size']
    seal = seal[offset:limit]

    return pages, seal


#
#
def pagesadmin(seal):
    req = request.values
    page = 1
    if 'p' in req and req['p']:
        page = int(req['p'])

    page_params = {
        'total_count': seal.count(),
        "page_size": 8,
        'page': page,
        'url': "/seal/htadmin?",
    }
    pages = iPagenation(page_params)
    # -1 - 30,30 - 60 ,60 - 90
    offset = (page - 1) * page_params['page_size']
    limit = page * page_params['page_size']
    seal = seal[offset:limit]

    return pages, seal


#
#
# def pagesupadte(member):
#     req = request.values
#     page = 1
#     if 'p' in req and req['p']:
#         page = int(req['p'])
#
#     page_params = {
#         'total_count': member.count(),
#         "page_size": 1,
#         'page': page,
#         'url': "/member/admin?",
#     }
#     pages = iPagenation(page_params)
#     # -1 - 30,30 - 60 ,60 - 90
#     offset = (page - 1) * page_params['page_size']
#     limit = page * page_params['page_size']
#     member = member[offset:limit]


@seal_page.route('/htadmin', methods=['GET', 'POST'])
def sealhtadmin():
    ht = SealOrder.query.filter_by(type="合同", mark=2).order_by(SealOrder.created_time.desc()).limit(8)
    pages, ht = pagesadmin(ht)

    return ops_render("/admin/sealadmin.html", {"pages": pages, "ht": ht})


@seal_page.route('/htsearch', methods=['GET', 'POST'])
def sealhtsearch():
    starttime = request.args.get('starttime')
    endtime = request.args.get('endtime')

    ht = SealOrder.query.filter(
        SealOrder.created_time.between(starttime, endtime), SealOrder.type == "合同", SealOrder.mark == 2).order_by(
        SealOrder.created_time.desc())

    pages, ht = pagessearch(ht, starttime, endtime)

    return ops_render("/admin/sealadmin.html", {"pages": pages, "ht": ht, "stime": starttime, "etime": endtime})


# 汇总Excel数据
# def make_excel_list(data, fields, column_names):
#     list_data = []
#
#     list_data.append(column_names)
#     for item in data:
#         tmp = []
#         for fi in fields:
#             tmp.append(getattr(item,fi))
#         list_data.append(tmp)
#         print(list_data)
#     return list_data

def make_excel_list(data, column_names):
    list_data = []
    list_data.append(column_names)
    for item in data:
        tmp = [item.htsn, item.name, item.project, item.aname, item.bname, item.filename, item.filenum, item.num,
               item.dfnum, item.cwnum, item.cdnum, item.creater.nickname, item.creater.company, item.creater.department]
        list_data.append(tmp)
    return list_data


excel.init_excel(app)


@seal_page.route("/export", methods=['GET'])
def export_records():
    starttime = request.args.get('starttime')
    endtime = request.args.get('endtime')

    query_sets = SealOrder.query.filter(
        SealOrder.created_time.between(starttime, endtime), SealOrder.type == "合同", SealOrder.mark == 2).order_by(
        SealOrder.created_time.desc()).all()
    column_names = ['合同编号', '合同名称', '项目', '甲方名称', '乙方名称', '附件名称', '合同页数', '总分数', '对方份数', '财务份数', '存档份数', '申请人', '申请公司',
                    '申请部门']
    excel_data = make_excel_list(query_sets, column_names)

    # app.logger.info(excel_data)

    return excel.make_response_from_array(excel_data, file_type='xls',
                                          file_name="导出数据",
                                          sheet_name='合同信息')
